using System;
using System.Collections.Generic;
using System.Text;

using System.Xml;

//using NUnit.Framework;


using OWED.Network.Messages;
using OWED.Network.Messages.General;
using OWED.Network.Messages.Reply;
using OWED.Network;
using OWED.Backend;

using System.Threading;

namespace OWED.Backend
{
    class MessageHandler : Server
    {
        public MessageHandler(int port) : base(port) { }

        public delegate IProtocolItem waitAsParam(Object o);
        public delegate void replyAsParam(Object o, IProtocolItem ipi);

        /// <summary>
        /// This is the method that overrides the server's to 
        /// allow connections between a database and clients.
        /// It will be called upon the instantiation of this
        /// class, since it is a child of server.
        /// Wait and Reply come from the server and must be
        /// passed into the created session.
        /// </summary>
        /// <param name="me"></param>
        protected override void ConnectionLoop(Object me)
        {
            // these exist simply to pass though to the session.
            waitAsParam DelWait = Wait;
            replyAsParam DelReply = Reply;

            Session s = new Session(me, DelWait, DelReply);

            s.Login();
            while (s.IsLoggedIn)
            {
                s.HandleOneMessage();
            }
            Console.WriteLine("done!");
            return;
        }

        static void Main(String[] args)
        {
            MessageHandler s = null;
            while (true)
            {
                try
                {
                    s = new MessageHandler(1771);
                    EventWaitHandle wait = new EventWaitHandle(false, EventResetMode.AutoReset);

                    Console.ReadLine();

                    s.Dispose();
                }
                catch (Exception)
                {
                    try
                    {
                        s.Dispose();
                    }
                    catch (Exception)
                    {
                        s = null;
                    }
                }
            }
        }

        protected override IProtocolItem Wait(object me)
        {
            IProtocolItem msg = base.Wait(me);
            Console.WriteLine("-------------");
            Console.WriteLine("Got: {0}", msg.ToXml().OuterXml);
            Console.WriteLine("-------------\n\n");
            return msg;
        }

        protected override void Reply(object me, IProtocolItem reply)
        {
            Console.WriteLine("-------------");
            Console.WriteLine("Sending: {0}", reply.ToXml().OuterXml);
            Console.WriteLine("-------------\n\n");
            base.Reply(me, reply);
        }
    }
}